package com.tt.payee.utils;

import com.tt.payee.domain.SysUser;
import com.tt.payee.domain.TbUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT生成令牌、验证令牌、获取令牌
 */
@Component
public class JwtTokenUtil {
    //私钥
    private static final String SECRET_KEY = "zheshimiyao123";

    // 过期时间 毫秒,设置默认1周的时间过期
    private static final long EXPIRATION_TIME = 3600000L * 12;//3600000L * 24 * 7;

    /**
     * 生成令牌
     *
     * @param tbUser 用户
     * @return 令牌
     */
    public static String generateBackendUserToken(TbUser tbUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", tbUser.getUserId());
        claims.put("username", tbUser.getUsername());
        claims.put("loginVersion", tbUser.getLoginVersion());
        claims.put("userType",1);  //1：后台tb用户；2：小程序app等sys用户
        return generateToken(claims);
    }

    /**
     * 生成令牌
     *
     * @param sysUser 用户
     * @return 令牌
     */
    public static String generateTerminalUserToken(SysUser sysUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", sysUser.getUid());
        claims.put("username", sysUser.getUsername());
        claims.put("loginVersion", sysUser.getLoginVersion());
        claims.put("userType",2);  //1：后台tb用户；2：小程序app等sys用户
        return generateToken(claims);
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public static String getUsernameFromToken(String token)throws Exception {
        Claims claims = getClaimsFromToken(token);
        String username = "";
        if(claims.get("username") != null){
            username = claims.get("username").toString();
        }
        return username;
    }

    /**
     * 从令牌中获取id
     *
     * @param token 令牌
     * @return id
     */
    public static String getIdFromToken(String token)throws Exception {
        Claims claims = getClaimsFromToken(token);
        String id = claims.get("id").toString();
        return id;
    }

    /**
     * 从令牌中获取userType
     *
     * @param token 令牌
     * @return id
     * 1：后台tb用户；2：小程序app等sys用户
     */
    public static int getUserTypeFromToken(String token)throws Exception {
        Claims claims = getClaimsFromToken(token);
        int userType = Integer.parseInt(claims.get("userType").toString());
        return userType;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public static Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            new Throwable(e);
        }
        return true;
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
//    public Boolean validateToken(String token, UserDetails userDetails) throws Exception {
//        AuthUser user = (AuthUser) userDetails;
//        String username = getUsernameFromToken(token);
//        return (username.equals(user.getUsername()) && !isTokenExpired(token));
//    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private static String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public static Claims getClaimsFromToken(String token) throws Exception {
        Claims claims = null;
        claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims;
    }

    public static void main(String[] args) throws Exception {

        Map<String, Object> claims = new HashMap<>(2);
        claims.put("id", 201);
        claims.put("loginVersion", new Date());
        Date expirationDate = new Date(System.currentTimeMillis() + 60000L);
        System.out.println(expirationDate);
        //String token = Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
        //System.out.println(token);

        //String token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpblZlcnNpb24iOjAsImlkIjo0NTc2LCJ1c2VyVHlwZSI6MiwiZXhwIjoxNTkzNTQxMjk3LCJ1c2VybmFtZSI6Im9ZblQyc3NkQUpUdnVtdXAzRHZxb18wSWwwTkkifQ.vExjaISLKdzOE94lH5fP-d11EbpxIuObluI9aMjCMXXPmAA5apCwrNgaExTXJK9elov5JJSE7KvsYXbBDK6iKw";
//        Claims claims = null;
//        claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
//        String exp = claims.get("exp").toString();
//        System.out.println(JSON.toJSONString(claims));
//        System.out.println(exp);

       // System.out.println(JwtTokenUtil.isTokenExpired(token));

    }

}